package ohc.login.mixin;

import com.mojang.brigadier.ParseResults;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import ohc.login.FakePlayerManager;
import ohc.login.PlayerDataManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

/**
 * 拦截 /player <玩家名> spawn 命令，并处理假人自动登录
 */
@Mixin(net.minecraft.server.command.CommandManager.class)
public class CommandExecutionMixin {
    
    private static final long ADMIN_UID = 5558;
    
    @Inject(method = "execute", at = @At("HEAD"), cancellable = true)
    private void onExecuteCommand(ParseResults<ServerCommandSource> parseResults, String command, CallbackInfo ci) {
        ServerCommandSource source = parseResults.getContext().getSource();
        if (shouldBlockPlayerSpawnCommand(source, command)) {
            ci.cancel();
            return;
        }
        
        // 检测假人生成命令，记录待自动登录
        String fakePlayerName = FakePlayerManager.INSTANCE.parsePlayerSpawnCommand(command);
        if (fakePlayerName != null) {
            FakePlayerManager.INSTANCE.scheduleFakePlayerLogin(fakePlayerName);
        }
    }
    
    /**
     * 检查是否应该拦截 /player spawn 命令
     */
    private boolean shouldBlockPlayerSpawnCommand(ServerCommandSource source, String command) {
        String trimmed = command.trim();
        
        // 检查是否是 /player 命令
        if (!trimmed.toLowerCase().startsWith("player ")) {
            return false;
        }
        
        String[] parts = trimmed.split("\\s+");
        // 格式: player <name> spawn [...]
        if (parts.length < 3) {
            return false;
        }
        
        if (!parts[2].equalsIgnoreCase("spawn")) {
            return false;
        }
        
        String targetName = parts[1];
        
        // 检查目标玩家是否已在线
        if (source.getServer().getPlayerManager().getPlayer(targetName) != null) {
            ServerPlayerEntity player = source.getPlayer();
            if (player != null) {
                player.sendMessage(
                    Text.literal("§c玩家 " + targetName + " 已在线，无法召唤").formatted(Formatting.RED)
                );
            }
            return true;
        }
        
        // 检查执行者是否有权限
        if (hasAdminPermission(source)) {
            return false;
        }
        
        // 检查目标玩家名是否是已记录的玩家
        if (isRecordedPlayer(source.getServer(), targetName)) {
            ServerPlayerEntity player = source.getPlayer();
            if (player != null) {
                player.sendMessage(
                    Text.literal("§c无法召唤已绑定账号的玩家: " + targetName).formatted(Formatting.RED)
                );
            }
            return true;
        }
        
        return false;
    }
    
    /**
     * 检查玩家名是否已被记录
     */
    private boolean isRecordedPlayer(net.minecraft.server.MinecraftServer server, String playerName) {
        return PlayerDataManager.INSTANCE.getPlayerDataByName(server, playerName) != null;
    }
    
    /**
     * 检查是否有管理权限
     */
    private boolean hasAdminPermission(ServerCommandSource source) {
        // 控制台执行不拦截
        if (!source.isExecutedByPlayer()) {
            return true;
        }
        
        // OP 权限
        if (source.hasPermissionLevel(2)) {
            return true;
        }
        
        ServerPlayerEntity player = source.getPlayer();
        if (player == null) {
            return true;
        }
        
        // 特权 UID
        PlayerDataManager.PlayerData data = PlayerDataManager.INSTANCE.getPlayerData(player.getUuid());
        return data != null && data.getApiUid() == ADMIN_UID;
    }
}
